package com.example.qqviewspringboot.service;

import com.example.qqviewspringboot.data.Notification;
import com.example.qqviewspringboot.data.User;
import com.example.qqviewspringboot.repository.NotificationRepository;
import com.example.qqviewspringboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@Service
public class NotificationService {
    private static final Logger log = LoggerFactory.getLogger(NotificationService.class);

    @Autowired
    private NotificationRepository notificationRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 创建通知
     */
    public Notification createNotification(Long recipientId, String message, String type) {
        // 参数校验
        if (recipientId == null || message == null || message.trim().isEmpty()) {
            throw new IllegalArgumentException("Recipient ID and message must not be null or empty");
        }
        if (type == null || type.trim().isEmpty()) {
            throw new IllegalArgumentException("Type must not be null or empty");
        }

        // 验证接收者是否存在
        User recipient = userRepository.findById(recipientId)
                .orElseThrow(() -> new IllegalArgumentException("User with ID " + recipientId + " not found"));

        try {
            // 创建通知
            Notification notification = new Notification();
            notification.setRecipientId(recipientId);
            notification.setMessage(message);
            notification.setType(type);
            notification.setUser(recipient);

            // 保存通知
            Notification savedNotification = notificationRepository.save(notification);

            // 日志记录
            log.info("Notification created for recipientId {} with type {} and message: {}", recipientId, type, message);

            return savedNotification; // 返回保存的通知
        } catch (Exception e) {
            log.error("Failed to create notification for recipientId {}: {}", recipientId, e.getMessage());
            throw new RuntimeException("Failed to create notification", e);
        }
    }

    /**
     * 获取好友申请通知
     */
    public List<Notification> getFriendRequestNotifications(Long userId) {
        return notificationRepository.findByRecipientIdAndType(userId, "FRIEND_REQUEST");
    }
}
